package com.kasax.plugin.app.transform

import com.android.build.api.transform.*
import com.android.build.gradle.internal.pipeline.TransformManager
import com.android.utils.FileUtils
import com.google.common.collect.ImmutableSet
import com.kasax.plugin.app.GrokTrackTimeExtension
import com.kasax.plugin.app.LogUtils
import org.gradle.api.Project

/**
 *
 */
class GrockTransform extends Transform {
    String TAG = "GrockTransform"
    Project project
    GrokTrackTimeExtension trackTimeExtension

    GrockTransform(Project proj, GrokTrackTimeExtension grokTrackTimeExtension) {
        this.project = proj
        this.trackTimeExtension = grokTrackTimeExtension
    }

    @Override
    String getName() {
        return "GrockTransform"
    }

    @Override
    Set<QualifiedContent.ContentType> getInputTypes() {
        return TransformManager.CONTENT_CLASS
    }

    @Override
    Set<? super QualifiedContent.Scope> getScopes() {
        return ImmutableSet.of(QualifiedContent.Scope.PROJECT)
    }

    @Override
    boolean isIncremental() {
        return false
    }

    @Override
    void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException {
        super.transform(transformInvocation)

        LogUtils.d(getName(), "------------ ------------  transform 开始  ------------ ------------  ")
        def inputs = transformInvocation.inputs
        def outputs = transformInvocation.outputProvider
        inputs.forEach { TransformInput input ->
            // 依赖的jar包内容保持不变
            LogUtils.d(getName(), "handle jarInputs")
            input.jarInputs.forEach { JarInput jarInput ->
                // 传递给下一个任务
                def dest = outputs.getContentLocation(jarInput.name, jarInput.contentTypes, jarInput.scopes, Format.JAR)
                FileUtils.copyFile(jarInput.file, dest)
            }
            LogUtils.d(getName(), "handle directoryInputs")

            // 当前项目源码
            input.directoryInputs.forEach { DirectoryInput directoryInput ->
                // 处理字节码
                handleDirInput(directoryInput)
                // 传递给下一个任务
                def dest = outputs.getContentLocation(directoryInput.name, directoryInput.contentTypes,
                        directoryInput.scopes, Format.DIRECTORY)
                FileUtils.copyDirectory(directoryInput.file, dest)
            }
        }

        LogUtils.d(getName(), "------------ ------------  transform 结束  ------------ ------------  ")
    }

    void handleDirInput(DirectoryInput directoryInput) {
//        def files = fileRecurse(directoryInput.file.absolutePath, new ArrayList<>())
    }
}